package com.gui.nio;

import cn.hutool.core.lang.Assert;
import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

@Slf4j
public class ByteBufferDemo1 {

    public static void main(String[] args) {
        testByteBuffer();
    }

    private static void testByteBuffer() {
        FileChannel fileChannel = null;
        try {
            URL url = ByteBufferDemo1.class.getResource("/data.txt");
            Assert.notNull(url);
            String path = url.getPath();
            fileChannel = new FileInputStream(path).getChannel();
            // 准备一个缓冲区 使用的是java的堆内存
            ByteBuffer buffer = ByteBuffer.allocate(100);
            while (true) {
                // len 就是读取了多少个字节 -1 代表没有字节数了
                int len = fileChannel.read(buffer);
                log.debug("读取到的字符数：{}", len);
                if (len == -1) {
                    break;
                }
                // 切换至读模式
                buffer.flip();
                byte[] bytes = new byte[len];
                int index = 0;
                while (buffer.hasRemaining()) {
                    bytes[index++] = buffer.get();
                }
                log.debug("读取到的数据为：{}", new String(bytes));
                buffer.clear();
            }
        } catch (Exception e) {
            log.error("文件读取失败", e);
        } finally {
            if (fileChannel != null) {
                try {
                    fileChannel.close();
                } catch (IOException e) {
                    log.error("关闭资源异常", e);
                }
            }
        }
    }
}
